package app.v1.common.service.impl;

import app.v1.common.domain.ao.resource.ResourceCreateAo;
import app.v1.common.domain.pojo.Resource;
import app.v1.common.domain.vo.resource.ResourceCreateVo;
import app.v1.common.service.ResourceService;
import com.gitee.feizns.quickstart.web.restful.Rests;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * 资源服务impl
 * @author feizns
 * @since 2023/06/11
 */
@Service
public class ResourceServiceImpl implements ResourceService {

    @Override
    public ResourceCreateVo create(ResourceCreateAo ao) {
        return saveToFile(ao);
    }

    @Override
    public String getAbUrlById(Long id) {
        return Rests.getById(Resource.class, id).getAbUrl();
    }

    /**
     * 资源文件保存路径
     */
    @Value("${resource-file-save-path}")
    private String resourceFileSavePath;

    /**
     * 资源文件域名路径
     */
    @Value("${resource-file-domain-path}")
    private String resourceFileDomainPath;

    /**
     * 保存到文件
     */
    @SneakyThrows
    private ResourceCreateVo saveToFile(ResourceCreateAo ao) {
        MultipartFile file = ao.getFile();
        String filename = generateFilename(file.getOriginalFilename());
        Resource resource = new Resource();
        resource.setKey(filename);
        resource.setAbUrl(String.format("%s%s", resourceFileDomainPath, filename));
        resource.insert();
        file.transferTo(new File(resourceFileSavePath, filename));
        return new ResourceCreateVo(filename, resource.getAbUrl());
    }

    /**
     * 生成文件名
     * @return {@link String}
     */
    private static String generateFilename(String filename) {
        return UUID.randomUUID() + "-" + System.currentTimeMillis() + StringUtils.getFilenameExtension(filename);
    }

}
